package com.xxx.course.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import com.xxx.course.service.OssService;
import com.xxx.course.utils.OssPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadAvatarFile(MultipartFile file) {
        String endpoint = OssPropertiesUtils.END_POINT;
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维
        String accessKeyId = OssPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = OssPropertiesUtils.ACCESS_KEY_SECRET;
        // 填写Bucket名称，例如examplebucket。
        String bucketName = OssPropertiesUtils.BUCKET_NAME;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            InputStream inputStream = file.getInputStream();

            String filename =UUID.randomUUID().toString().replaceAll("-","")+ file.getOriginalFilename();
            //按照日期分类
            String datePath = new DateTime().toString("yyyy/MM/dd");
            filename=datePath+"/"+filename;
            // 创建PutObject请求。
            ossClient.putObject(bucketName, filename, inputStream);
            ossClient.shutdown();
            String url="https://"+bucketName+"."+endpoint+"/"+filename;
            return url;
        } catch (Exception e) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            return null;
        }

    }
}
